package com.gexin.core.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.gexin.common.AppConst;
import com.gexin.common.GeXinSessionKit;
import com.gexin.common.model.ApiResponse;
import com.gexin.common.utils.StringUtil;
import com.gexin.model.weixin.WeixinUser;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

/**
 * APP拦截器
 *
 * @author 肖得明 2016-12-29
 */
public class XAppSafeInterceptor implements Interceptor {
	private static final Log log = Log.getLog(XAppSafeInterceptor.class);

	/**
	 * 小程序post提交请求方式接口后台需从流中获取参数
	 *
	 * @return
	 */
	public JSONObject getRequestData(HttpServletRequest request) {
		try {
			// 获取文件流
			InputStream inStream = request.getInputStream();
			ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = inStream.read(buffer)) != -1) {
				outSteam.write(buffer, 0, len);
			}
			// 转换格式
			String result = new String(outSteam.toByteArray(), "utf-8");
			JSONObject json = JSONObject.parseObject(result);
			return json;
		} catch (Exception e) {
			e.printStackTrace();
			return new JSONObject();
		}
	}

	@Override
	public void intercept(Invocation paramInvocation) {
		try {
			Controller controller = paramInvocation.getController();
			Boolean isXapp = "xapp".equals(controller.getHeader("source"));
			// String token = controller.getRequest().getParameter("token");
			String token = controller.getHeader("user-token");
			controller.setAttr("user-token",token);
			if (isXapp) {
				if (StringUtil.isBlank(token)) {
					JSONObject json = getRequestData(controller.getRequest());
					if (json != null) {
						token = json.getString("user-token");
					}
				}
				// 如果参数为空
				if (StringUtil.isBlank(token)) {
					controller.renderJson(new ApiResponse(101, AppConst.ApiErrorMessage.get(101)));
					return;
				}
				// 判断sessionId的有效性
				String sessionJson = GeXinSessionKit.getSession(token);
				if (StrKit.isBlank(sessionJson)) {
					controller.renderJson(new ApiResponse(102, AppConst.ApiErrorMessage.get(102)));
					return;
				}
			} else {
				//app 的逻辑
				//如果参数为空
				if (StringUtil.isBlank(token)) {
					controller.renderJson(new ApiResponse(101, AppConst.ApiErrorMessage.get(101)));
					return;
				}
				//判断token的有效性
				Integer user_id = WeixinUser.dao.isActiveToken(token);
				if (user_id == null) {
					controller.renderJson(new ApiResponse(102, AppConst.ApiErrorMessage.get(102)));
					return;
				}
				//controller.setAttr("user_id", "oFcHvsgunqBDnlzFVWe4Wf-HtvPU");
				controller.setAttr("user_id", user_id);
			}


			// SUCCESS
			paramInvocation.invoke();
		} catch (Exception e) {
			doLog(paramInvocation, e);
			paramInvocation.getController().renderJson(new ApiResponse(500, AppConst.ApiErrorMessage.get(500)));// 服务器内部错误
		}
	}

	private void doLog(Invocation ai, Exception e) {
		// 开发模式
		if (JFinal.me().getConstants().getDevMode()) {
			e.printStackTrace();
		}
		StringBuilder sb = new StringBuilder("\n---Exception Log Begin---\n");
		sb.append("Controller:").append(ai.getController().getClass().getName()).append("\n");
		sb.append("Method:").append(ai.getMethodName()).append("\n");
		sb.append("Exception Type:").append(e.getClass().getName()).append("\n");
		sb.append("Exception Details:");
		log.error(sb.toString(), e);
	}
}